package small.common.statistic.data;

import small.common.statistic.base.MetricEvent;

import java.util.concurrent.atomic.LongAdder;

/**
 * 计数器
 *
 * @author jinzhou
 * @data 2023/4/7 11:05
 */
public class MetricBucket {

    private final LongAdder[] counters;

    public MetricBucket() {
        MetricEvent[] events = MetricEvent.values();
        this.counters = new LongAdder[events.length];
        for (MetricEvent event : events) {
            counters[event.ordinal()] = new LongAdder();
        }
    }

    /**
     * 重置当前窗口所有的值
     * @return
     */
    public MetricBucket reset() {
        for (MetricEvent event : MetricEvent.values()) {
            counters[event.ordinal()].reset();
        }
        return this;
    }

    /**
     * 重置指定计数器
     * @param bucket
     * @return
     */
    public MetricBucket reset(MetricBucket bucket) {
        for (MetricEvent event : MetricEvent.values()) {
            counters[event.ordinal()].reset();
            counters[event.ordinal()].add(bucket.get(event));
        }
        return this;
    }


    /**
     * 添加通过数量
     * @param n
     */
    public void addPass(int n) {
        add(MetricEvent.PASS, n);
    }

    /**
     * 添加异常数量
     * @param n
     */
    public void addException(int n) {
        add(MetricEvent.EXCEPTION, n);
    }

    /**
     * 添加统计类型值
     */
    public MetricBucket add(MetricEvent event, long n) {
        counters[event.ordinal()].add(n);
        return this;
    }

    /**
     * 获取通过统计值
     */
    public long pass() {
        return get(MetricEvent.PASS);
    }

    /**
     * 获取异常统计值
     */
    public long exception() {
        return get(MetricEvent.EXCEPTION);
    }

    /**
     * 获取指定类型统计值
     */
    public long get(MetricEvent event) {
        return counters[event.ordinal()].sum();
    }

    @Override
    public String toString() {
        return "pass: " + pass() + ", exception: " + exception() ;
    }
}
